﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using SST.WebClient.Data;
using System.Windows.Threading;
using SST.Phone.Model.DAO;
using SST.Phone.Model.VO;
using SST.WebClient;
using SST.Phone.Util;
using System.Windows.Data;

namespace SST.Phone
{
    public partial class MainPage : PhoneApplicationPage
    {
        public const string APP_BUTTON_URI_STOP = "/Resources/appbar.transport.stop.rest.png";
        public const string APP_BUTTON_URI_PLAY = "/Resources/appbar.transport.play.rest.png";
        public const string APP_BUTTON_URI_SEND = "/Resources/appbar.send.text.rest.png";

        /// <summary>
        /// Application bar play button
        /// </summary>
        //private ApplicationBarIconButton btnPlay;

        /// <summary>
        /// To trigger deduct now playing duration
        /// </summary>
        private DispatcherTimer nowPlayingDurationTimer = new DispatcherTimer();

        /// <summary>
        /// Different view has different appliation bar
        /// </summary>
        private List<ApplicationBar> appBarList = new List<ApplicationBar>();

        /// <summary>
        /// Application bar send button
        /// </summary>
        private ApplicationBarIconButton btnSend;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            nowPlayingDurationTimer.Tick += new EventHandler(nowPlayingDurationTimer_Tick);
            nowPlayingDurationTimer.Interval = new TimeSpan(0, 0, 1);
            nowPlayingDurationTimer.Start();
        }

        #region Initialization
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            App.ViewModel.Message = null;
            InitAppBar();

            //refresh settings
            LoadSettings();

            //load view model data
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
            else
                App.ViewModel.LoadChatList();


            UpdateAppBar();
            LoginUser();
        }

        /// <summary>
        /// Initialize application bar (bottom bar), all views
        /// http://stackoverflow.com/questions/5334574/applicationbariconbutton-is-null
        /// </summary>
        private void InitAppBar()
        {
            appBarList.Clear();
            for (int i = 0; i < MainPanorama.Items.Count; i++)
            {
                ApplicationBar appBar = new ApplicationBar();
                appBar.Mode = ApplicationBarMode.Minimized;

                //if (btnPlay == null)
                //{
                //    btnPlay = new ApplicationBarIconButton(new Uri(APP_BUTTON_URI_STOP, UriKind.Relative));
                //    btnPlay.Click += new EventHandler(btnPlay_Click);
                //    btnPlay.Text = "stop";
                //    btnPlay.IsEnabled = false;
                //}
                //appBar.Buttons.Add(btnPlay);

                ApplicationBarMenuItem settingMenu = new ApplicationBarMenuItem();
                settingMenu.Text = "Settings";
                settingMenu.Click += (s, e) =>
                {
                    NavigationService.Navigate(new Uri("/View/SettingPage.xaml", UriKind.RelativeOrAbsolute));
                };
                appBar.MenuItems.Add(settingMenu);

                if (i == 2)
                {
                    //chat page, add send button if is available
                    btnSend = new ApplicationBarIconButton(new Uri(APP_BUTTON_URI_SEND, UriKind.Relative))
                    {
                        Text = "send"
                    };
                    btnSend.Click += new EventHandler(btnSend_Click);
                    btnSend.IsEnabled = false;
                    appBar.Buttons.Add(btnSend);
                    appBar.Mode = ApplicationBarMode.Default;
                }
                appBarList.Add(appBar);
            }
        }

        /// <summary>
        /// Change application bar according to current view and other information
        /// </summary>
        private void UpdateAppBar()
        {
            btnSend.IsEnabled = App.ViewModel.IsEnableChatSend;
            ApplicationBar = appBarList[MainPanorama.SelectedIndex];
        }

        /// <summary>
        /// Login user using username and password in setting
        /// </summary>
        private void LoginUser()
        {
            App.ViewModel.IsEnableChatSend = false;
            UpdateAppBar();

            UserAccount user = new UserAccount();

            SettingsDAO settingDAO = new SettingsDAO(App.DB);

            user.Username = settingDAO.LoadValue(SettingItem.SETTING.USERNAME);
            user.Password = settingDAO.LoadValue(SettingItem.SETTING.PASSWORD);

            App.ViewModel.User = user;
            if (user.Username == null || user.Username == "")
                return;

            App.ViewModel.AddLoadingCount();
            AccountService service = new AccountService();
            service.LoginAsyncCompleted += (s, e) =>
            {
                if (e.Success)
                {
                    App.ViewModel.Message = "Your are logged in";
                    App.ViewModel.IsEnableChatSend = true;
                    UIHelper.Debug("userpw=" + App.ViewModel.User.UserPw);
                }
                else
                {
                    App.ViewModel.Message = "Login failed";
                    App.ViewModel.IsEnableChatSend = false;
                }
                UpdateAppBar();
                App.ViewModel.DeductLoadingCount();
            };
            service.LoginAsync(user);
        }

        /// <summary>
        /// Load settings, init this app
        /// </summary>
        private void LoadSettings()
        {
            SettingsDAO settingDAO = new SettingsDAO(App.DB);
            string chatRefresh = settingDAO.LoadValue(SettingItem.SETTING.CHAT_REFRESH);
            int ChatRefreshTime = -1;
            try
            {
                if (chatRefresh != null)
                    ChatRefreshTime = int.Parse(chatRefresh);
            }
            catch (Exception ex)
            {
                UIHelper.Debug(ex);
            }
            App.ViewModel.ChatRefreshTime = ChatRefreshTime;

            string _showTray = settingDAO.LoadValue(SettingItem.SETTING.SHOW_TRAY);
            if (_showTray == "true")
                App.ViewModel.ShowTray = true;
            else
                App.ViewModel.ShowTray = false;
        }
        #endregion

        #region Event handlers
        //private void player_CurrentStateChanged(object sender, RoutedEventArgs e)
        //{
        //    if (btnPlay != null)
        //    {
        //        App.ViewModel.Message = "state=" + player.CurrentState.ToString();
        //        if (player.CurrentState == MediaElementState.Playing || player.CurrentState == MediaElementState.Buffering)
        //        {
        //            btnPlay.IsEnabled = true;
        //            btnPlay.IconUri = new Uri(APP_BUTTON_URI_STOP, UriKind.Relative);
        //            btnPlay.Text = "stop";
        //            App.ViewModel.IsPlaying = true;
        //        }
        //        else if (player.CurrentState == MediaElementState.Stopped || player.CurrentState == MediaElementState.Paused)
        //        {
        //            btnPlay.IsEnabled = true;
        //            btnPlay.IconUri = new Uri(APP_BUTTON_URI_PLAY, UriKind.Relative);
        //            btnPlay.Text = "play";
        //            App.ViewModel.IsPlaying = false;
        //        }
        //        else
        //        {
        //            btnPlay.IsEnabled = false;
        //            App.ViewModel.IsPlaying = false;
        //        }
        //    }
        //}

        //private void btnPlay_Click(object sender, EventArgs e)
        //{
        //    if (App.ViewModel.IsPlaying)
        //        player.Stop();
        //    else
        //        player.Play();
        //}

        /// <summary>
        /// When thankyou image button clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnThankyou_Click(object sender, RoutedEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            webBrowserTask.Uri = new Uri(Common.SST_URL, UriKind.Absolute);
            webBrowserTask.Show();
        }

        /// <summary>
        /// Timer trigger deduct now playing duration
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void nowPlayingDurationTimer_Tick(object sender, EventArgs e)
        {
            if (App.ViewModel.NowPlaying == null || App.ViewModel.NowPlaying.Track == null || App.ViewModel.NowPlaying.Track.Duration <= 0)
                return;
            App.ViewModel.NowPlaying.Track.Duration--;
        }

        /// <summary>
        /// When view is changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateAppBar();
        }

        /// <summary>
        /// When send chat button clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnSend_Click(object sender, EventArgs e)
        {
            btnSend.IsEnabled = false;
            txtChatMessage.IsEnabled = false;
            ChatService service = new ChatService();
            service.SendAsyncCompleted += (s, sendEventArgs) =>
            {
                btnSend.IsEnabled = true;
                txtChatMessage.IsEnabled = true;
                if (!sendEventArgs.Success)
                    App.ViewModel.Message = "Message send failed";
                else
                {
                    txtChatMessage.Text = "";
                    App.ViewModel.LoadChatList();
                }
            };
            service.SendAsync(txtChatMessage.Text, App.ViewModel.User);
        }
        #endregion
    }
}